﻿using B.S.DataBasic.Domain.RBAC;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace B.S.DataBasic.Infrastructure.Implement
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly DataDbContext db;
        public BaseRepository(DataDbContext db)
        {
            this.db = db;
        }
        /// <summary>
        /// 查询多条
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>().AsQueryable();
        }
        /// <summary>
        /// 查询单条
        /// </summary>
        /// <param name="except"></param>
        /// <returns></returns>
        public async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>返回</returns>
        public async Task<int> AddAsync(T entity)
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T entity)
        {
             db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }

        public int Update(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChanges();
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(T entity)
        {
            db.Set<T>().Remove(entity);
            return await db.SaveChangesAsync();
        }


        public T GetById(int id)
        {
            return db.Set<T>().Find(id);
        }


    }



}
